﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;

namespace _4chanManager.Logic
{
    public class GifConverter : IReportable
    {
        private string rootDirectory;
        private readonly List<string> _directoryList;
        private const string gifExt = ".gif";
        private const string webmExt = ".webm";
        public bool RemoveGifAfterConvert = true;
        public GifConverter(string rootDirectory)
        {
            this.rootDirectory = rootDirectory;
            _directoryList = new List<string>();
        }

        public void Start()
        {
            if (string.IsNullOrEmpty(rootDirectory))
            {
                SendMessage(string.Format("You need to specify a folder..."));
                return;
            }
            _directoryList.Add(rootDirectory);
            GetDirectoryStructure(rootDirectory);
            StartWork();
        }

        private void GetDirectoryStructure(string actualDirectory)
        {
            try
            {
                List<string> dirList = Directory.GetDirectories(actualDirectory).ToList();
                foreach (string dir in dirList)
                {
                    _directoryList.Add(dir);
                    GetDirectoryStructure(dir);
                }
            }
            catch (Exception)
            {
                _directoryList.Remove(actualDirectory);
            }

        }

        private void StartWork()
        {
            int iter = 0;
            foreach (string directory in _directoryList)
            {
                SendMainProgressChanged((int)(((decimal)iter++ / _directoryList.Count) * 100));
                HandleOneDirectory(directory);
            }
            SendTaskCompleted();
        }

        private void HandleOneDirectory(string dirPath)
        {
            try
            {
                List<string> files = Helpers.GetFilesInDirectory(dirPath, gifExt);
                int iter = 0;
                SendMessage(string.Format("Directory: {0}, Gif count: {1}", dirPath, files.Count));
                foreach (string file in files)
                {
                    SendSubProgressChanged((int)(((decimal)iter++ / files.Count) * 100));
                    string filename = Path.GetFileName(file).Replace(gifExt, string.Empty);
                    SendMessage(string.Format("Processing file : {0}", filename));
                    string path = Path.GetDirectoryName(file);

                    if (File.Exists(Helpers.CreateNewFilePath(path, filename, webmExt)))
                        continue;

                    Process process = new Process
                    {
                        StartInfo =
                        {
                            FileName = "ffmpeg.exe",
                            WorkingDirectory = dirPath,
                            CreateNoWindow = true,
                            RedirectStandardOutput = true,
                            UseShellExecute = false,
                            WindowStyle = ProcessWindowStyle.Hidden,
                            Arguments =
                                "-i \"" + file + "\" -c:v libvpx -crf 12 -b:v 500K \"" + Helpers.CreateNewFilePath(path, filename, webmExt) + "\""
                        }
                    };
                    process.Start();
                    while (!process.HasExited)
                    {
                        Thread.Sleep(10);
                    }

                    if (!RemoveGifAfterConvert) continue;
                    File.SetAttributes(file, 0);
                    File.Delete(file);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Somethning went wrong : " + e);
            }
        }

        private void SendMainProgressChanged(int progress)
        {
            if (MainProgressChanged != null)
                MainProgressChanged(progress);
        }
        private void SendSubProgressChanged(int progress)
        {
            if (SubProgressChanged != null)
                SubProgressChanged(progress);
        }
        private void SendMessage(string message)
        {
            if (AppendMessage != null)
                AppendMessage(message);
        }
        private void SendTaskCompleted()
        {
            if (TaskCompleted != null)
                TaskCompleted();
        }
        public event Helpers.ProgressChangedDelegate SubProgressChanged;
        public event Helpers.ProgressChangedDelegate MainProgressChanged;
        public event Helpers.MessageDelegate AppendMessage;
        public event Helpers.TaskCompletedDelegate TaskCompleted;
    }

}
